import React, { useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { filterActive } from '../../store/actions/filter'
import { todoClearDoned } from '../../store/actions/todo'

export default function TodoFooter() {
  const dispatch = useDispatch()
  const allTodo = useSelector((state) => state.todo)
  const active = useSelector((state) => state.filter)
  const [arr] = useState(['all', 'active', 'completed'])
  // 统计未完成数据：从所有数据里面找未完成的 length
  const leftCount = allTodo.filter((item) => !item.done).length
  const handleClearDoned = () => dispatch(todoClearDoned())
  // 1. 在 Redux 中准备一个全局变量，active 默认是空
  // 2. 用每一个 tab 的标记和 active 变量进行比较，命中就应用 selected class
  // 3. 点击每一个 tab 只需要把当前的标记给 Redux 中的变量 active
  const handleClick = (active) => dispatch(filterActive(active))
  return (
    <footer className='footer'>
      <span className='todo-count'>
        <strong>{leftCount}</strong> item left
      </span>
      <ul className='filters'>
        {arr.map((item) => (
          <li key={item} onClick={() => handleClick(item)}>
            <a className={item === active ? 'selected' : ''} href='#/'>
              {item.slice(0, 1).toUpperCase() + item.slice(1)}
            </a>
          </li>
        ))}
      </ul>
      <button className='clear-completed' onClick={handleClearDoned}>
        Clear completed
      </button>
    </footer>
  )
}
